package com.pengheng.service;

import com.pengheng.dao.CommentRepository;
import com.pengheng.po.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @remark
 * @Author pengheng
 * @date 2021/6/8 12:03
 */
@Service
public class CommentService {

    @Autowired
    private CommentRepository commentRepository;

    public void saveComment(Comment comment) {
        commentRepository.save(comment);
    }

    public void updateComment(Comment comment) {
        commentRepository.save(comment);
    }

    public void deleteCommentById(String id) { //调用dao
        commentRepository.deleteById(id);
    }

    public List<Comment> findCommentList() {
        return commentRepository.findAll();
    }

    public Comment findCommentById(String id) {
        return commentRepository.findById(id).get();
    }

    public Page<Comment> findCommentByUserid(String parentid, int page, int size) {
        return commentRepository.findByUserid(parentid, PageRequest.of(page - 1, size));
    }

    public Page<Comment> findCommentListPageByParentid(String parentid, int page, int size) {
        return commentRepository.findByParentid(parentid, PageRequest.of(page - 1, size));
    }

    public void updateCommentThumbupToIncrementingOld(String id) {
        Comment comment = commentRepository.findById(id).get();
        comment.setLikenum(comment.getLikenum() + 1);
        commentRepository.save(comment);
    }

    @Autowired
    private MongoTemplate mongoTemplate;

    public void updateCommentListnum(String id){
        Query query = Query.query(Criteria.where("_id").is(id));

        Update update = new Update();

        update.inc("likenum");

        mongoTemplate.updateFirst(query,update,"comment");
    }
}
